#!/usr/bin/perl -w

sub topParse{

	open(IN, "hello2");
	@heads;
	my %vertices;
	my @arr;
	while (<IN>){
		chomp($_);
		@arr = ();
		@arr = split(" ", $_);
		if ($#arr > 0){
#			print "this is the element $arr[0] ";
			push(@heads, $arr[0]);
		}
	}	
	close(IN);

	open(IN, "hello2");
	open(OUT, ">hello3");
	my $i = 1;
	my $topoline = "";
	my $line = <IN>;
	while (<IN>){
		chomp($_);
		@arr1 = ();
		$topoline = "";
		@arr1 = split(" ", $_);
		
		while (defined($item = shift @arr1)){
		    if (present($item, @heads)){
			if (! exists $vertices{$item}){
			    $vertices{$item} = $i++;
			}
			if ($topoline ne ""){
			    $topoline = $topoline." ".$vertices{$item};
			}else {
			    $topoline = $vertices{$item};
			}
		    } 
		}
		if ($topoline ne ""){
		    print "Hello man ".$topoline."\n";
		    $topoline = $topoline."\n";
		    print OUT $topoline;
		}
	    }
	close(OUT);
	close(IN);
    }

sub present{

    my $i = 0;
    my ($x, @elements) = @_;

    while( $i <= $#elements && ($elements[$i] ne $x)  ){

	++$i;
    }
    if ($i <= $#elements){

	return 1;
    }else{
	return 0;
    }
}

sub copy{

    open(IN, "hello4");
    open(OUT, ">$ARGV[0]");
    $vertices = $#heads+1;
    print OUT $vertices."\n";

    while (<IN>){
        chomp($_);
        print OUT $_."\n";
    }
    close(IN);
    close(OUT);
}

topParse();
system(`sort -k1n,1 hello3>hello4`);
copy();
